package com.leyou.trade.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.auth.utils.UserContext;
import com.leyou.common.exception.LyException;
import com.leyou.item.clients.ItemClient;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.dto.SkuDTO;
import com.leyou.trade.dto.OrderDTO;
import com.leyou.trade.entity.Order;
import com.leyou.trade.entity.OrderDetail;
import com.leyou.trade.entity.OrderLogistics;
import com.leyou.trade.entity.OrderStatus;
import com.leyou.trade.mapper.OrderMapper;
import com.leyou.trade.service.OrderDetailService;
import com.leyou.trade.service.OrderLogisticsService;
import com.leyou.trade.service.OrderService;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.AddressDTO;
import feign.FeignException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service

public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private ItemClient itemClient;

    @Autowired
    private OrderDetailService detailService;

    @Autowired
    private UserClient userClient;

    @Autowired
    private OrderLogisticsService logisticsService;



    @Override
    @Transactional
    public void creatOrder(OrderDTO orderDTO) {

        //key : skuId,value,sku数量
        Map<Long, Integer> cartsMap = orderDTO.getCarts();

        //减库存
        this.itemClient.minusStock(cartsMap);

        Order order = new Order();

        order.setStatus(1);
        order.setUserId(UserContext.getUser().getId());

        //全场包邮
        order.setPostFee(0L);
        order.setPaymentType(orderDTO.getPaymentType());


        if (CollectionUtils.isEmpty(cartsMap)) {
            throw new LyException(400, "下单失败，请求参数有误");
        }

        //sum(price*num)


        List<SkuDTO> skuDTOS = this.itemClient.listSkuByIds(new ArrayList<>(cartsMap.keySet()));

        if (skuDTOS == null) {
            throw new LyException(400, "下单失败");
        }

        long totalFee = 0;

        for (SkuDTO skuDTO : skuDTOS) {
            Long skuId = skuDTO.getId();

            totalFee += skuDTO.getPrice() * cartsMap.get(skuId);
        }

        order.setTotalFee(totalFee);
        order.setActualFee(totalFee);

        //保存订单，并回显id
        this.save(order);


        List<OrderDetail> orderDetails = skuDTOS.stream().map(skuDTO -> {

            //skuDTO ==> orderDetail
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(order.getOrderId());
            orderDetail.setSkuId(skuDTO.getId());
            orderDetail.setNum(cartsMap.get(skuDTO.getId()));
            orderDetail.setTitle(skuDTO.getTitle());
            orderDetail.setSpec(skuDTO.getSpecialSpec());
            orderDetail.setPrice(skuDTO.getPrice());
            orderDetail.setImage(StringUtils.substringBefore(skuDTO.getImages(), ","));

            return orderDetail;
        }).collect(Collectors.toList());

        //保存订单详情
        this.detailService.saveBatch(orderDetails);

        AddressDTO addressDTO = this.userClient.queryAddressById(UserContext.getUser().getId(), orderDTO.getAddressId());

        OrderLogistics orderLogistics = new OrderLogistics();
        //手动指派ID
        orderLogistics.setOrderId(order.getOrderId());

        BeanUtils.copyProperties(addressDTO, orderLogistics);


        //保存物流
        this.logisticsService.save(orderLogistics);


        throw new LyException(666,"恶意订单");

    }
}
